from turbogears import validators, widgets

from mnemoply import reports, model
from mnemoply.utils import IdsValidator, escape, getOne

_start_table_row = 5
_rows = 80

def generate_excel_commands(teacher, topic):
    # Header
    result = """
        <set range="teacher_name">%s</set>
        <set range="topic_name">%s</set>
    """ % (escape(teacher.title), escape(topic.name))

    # Select groups ruled by this teacher
    groups = list(model.Group.selectBy(teacher=teacher))

    students = []
    for group in groups:
        if topic not in list(group.topics):
            continue
        students.extend(
            [(x.student, group) for x in model.StudentInGroup.selectBy(group=group)]
        )

    students.sort(key=lambda x: x[0].surname)

    seen = set()
    row_n = _start_table_row
    for (student, group) in students:
        if student.id in seen:
            continue
        seen.add(student.id)

        mark = getOne(model.Mark.selectBy(student=student, topic=topic))

        if mark is not None:
            mark = mark.markType.title
        else:
            mark = '-'

        result += """
            <set range="A%(row)s">%(surname)s</set>\n
            <set range="B%(row)s">%(forename)s</set>\n
            <set range="C%(row)s">%(patronymic)s</set>\n
            <set range="D%(row)s">%(group)s</set>\n
            <set range="E%(row)s">%(mark)s</set>\n
        """ % dict(
            surname=escape(student.surname),
            forename=escape(student.forename),
            patronymic=escape(student.patronymic),
            group=group.name,
            mark=escape(mark),
            row=row_n,
        )

        row_n += 1

    result += "<hide_rows rows=\"A%d:A%d\" />\n" % (
        row_n,
        _start_table_row + _rows - 1,
    )

    return result

class TeacherMarksByTopicReport(reports.RDSReport):
    name = _("Teacher marks by topic")
    tag = "TeacherMarksByTopic"
    report_type = reports.RDSReportType.EXCEL
    template_module = "mnemoply.templates.reports.teacher_marks_by_topic"

    fields = [
        widgets.HiddenField(name="ids", label=_("IDs"),
            validator=IdsValidator),
        widgets.TextField(name='topic_id', label=_('Topic #'),
            validator=validators.Int(not_empty=True)),
    ]

    pass_functions = (generate_excel_commands,)

exposed = TeacherMarksByTopicReport()
